package com.foreknow.controller;

import com.foreknow.model.Guestbook;
import com.foreknow.service.GuestbookService;
import com.foreknow.service.impl.GuestbookServiceimpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

// Web 资源的跳转  有两种方式
// 1. 请求转发 （相当于站内跳转） 相当于一次请求
// 2. 重定向    （站内 站外 跳转） 两次请求


public class AddMessageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.setContentType("text/html;charset=utf-8");
            req.setCharacterEncoding("utf-8");
           PrintWriter out = resp.getWriter();
           String name=  req.getParameter("name");
        String phone=  req.getParameter("phone");
        String email=  req.getParameter("email");
        String title=  req.getParameter("title");
        String content=  req.getParameter("content");

        GuestbookService service =new GuestbookServiceimpl();
        Guestbook gb =new Guestbook();
          gb.setName(name);
          gb.setPhone(phone);
          gb.setEmail(email);
          gb.setTitle(title);
          gb.setContent(content);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
         gb.setCreatedtime(sdf.format(new Date()));
        boolean isRight=  service.save(gb);

        if (isRight){
//            out.print("<a href='/JavaWebDemo/user/get'>查询所有信息</a>");
            // 使用请求转发
            // 所有的url默认都是get请求
            // 只有表单才能设置post请求
        req.getRequestDispatcher("/user/get").forward(req,resp);

            // 重定向
//         也可以   resp.sendRedirect("/JavaWebDemo/user/get");
//            resp.sendRedirect( req.getContextPath()+"/user/get");
//            resp.sendRedirect("http://www.163.com");

        }else {
          out.print("失败");
        }





    }
}
